package ink.onei.production.controller;

import ink.onei.production.entity.AdminUser;
import ink.onei.production.exception.OperateException;
import ink.onei.production.service.ISystemService;
import ink.onei.production.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: dang
 * @Description: TODO
 * @Date: 2023/12/26 20:51 星期二
 */
@Controller
@RequestMapping("/system")
public class SystemController {

    @Autowired
    ISystemService userService;

    @RequestMapping("/AjaxLogin")
    @ResponseBody
    public Result<AdminUser> userLogin(@RequestBody AdminUser adminUser, HttpServletRequest req) {
        // @formatter:off
        Result<AdminUser> result = new Result<>();
        AdminUser loginUser = null;
        try {loginUser = userService.login(adminUser);} catch (OperateException e) {
            if (e.getMessage().equals("账号不存在")) result.setCode(401);
            else if (e.getMessage().equals("账号或密码错误")) result.setCode(402);
            result.setMsg(e.getMessage());
            return result;
            // @formatter:on
        }

        result.setMsg("登录成功");
        result.setObject(loginUser);
        HttpSession session = req.getSession();
        session.setAttribute("loginUser", loginUser.getUsername());
        return result;
    }
}
